<template>
    <div id="monitor-result-detail" class="move-box">
        <div class="left" id="silder-left">
            <div class="list-left">
                <h3 class="title">监控规则列表</h3>
                <div class="tree">
                    <ul>
                        <li
                            v-for="i in monitorRuleList"
                            @click="handleTreeClick(i)"
                            :key="i.ruleId"
                            :class="{ current: currentNode.ruleId === i.ruleId }"
                        >
                            <span class="name">{{ i.ruleName }}</span>
                            <span class="sum">{{ i.summaryCount }}</span>
                        </li>
                    </ul>
                </div>
            </div>
            <div class="move-btn" v-move-crosswise></div>
        </div>

        <div class="right silder-right">
            <h3 class="title">
                <span style="float: left">{{ currentNode.ruleName }}</span>
                <span v-show="currentNode.ruleName" class="progress progress-green" :style="{ width: `${greenNum * 2}px` }">{{ greenNum }}%</span>
                <span v-show="currentNode.ruleName" class="progress progress-red" :style="{ width: `${redNum * 2}px` }">{{ redNum }}%</span>
                <span v-show="currentNode.ruleName">
                    异常数: <b style="color: #e05548">{{ currentNode.summaryCount }}</b>
                </span>

                <span v-show="newCalcDate" style="float: right; padding-right: 10px">
                    <el-checkbox v-model="showException" @change="handleCheck">只展示异常结果</el-checkbox>

                    <span style="font-weight: normal; padding-left: 30px"> 比对时间: {{ newCalcDate }} </span>
                </span>
            </h3>

            <div class="table">
                <RiskTable
                    ref="risk-table"
                    :tableConfig="tableConfig"
                    :tableData="tableData"
                    :column="columns"
                    :paging="paging"
                    v-loading="tableLoading"
                    @page-change="getTableData"
                    :key="tableKey"
                    style="height: 100%"
                    :row-style="rowStyle"
                >
                </RiskTable>
            </div>
        </div>
    </div>
</template>
<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import RiskTable from '@/common/components/risk-table-plus.vue';
import { MonitorRuleRepVO, MonitorRuleVO } from '../vo/monitor-rule-setting';
import { dateFormat, timeFormat } from '@/utils/tools';
import { ColumnVO, PageVO, TableConfigVO } from '@/common/vo';
import { MonitorResultDTO, MonitorResultRepVO, MonitorResultVO } from '../vo/monitor-result';
import API from '../api/monitor-result';
import API2 from '../api/monitor-rule-setting';

@Component({ name: 'MonitorResultDetail', components: { RiskTable } })
export default class MonitorResultDetail extends Vue {
    monitorRuleList: MonitorRuleVO[] = [];
    currentNode: any = { ruleId: null };

    paging: PageVO = { currentPage: 1, pageSize: 25, total: 0 };
    tableLoading: boolean = false;
    tableConfig: TableConfigVO = {
        rowKey: 'ruleId', // 主键key
        allRowKeys: [], // 所有页数据的key集合
    };
    tableData: any[] = [];
    columns: ColumnVO[] = [];

    greenNum: number = 55;
    redNum: number = 45;
    showException: boolean = false;

    newCalcDate: string;

    mounted() {
        this.getLeftTree();
    }

    getLeftTree(): void {
        API.queryComparatorResultByGroup().then((res: any) => {
            this.monitorRuleList = res || [];
            // this.monitorRuleList = [{ ruleId: '81', ruleName: '11dsad' }];
        });
    }

    /**
     * 左侧点击事件
     */
    async handleTreeClick(node: any): Promise<any> {
        this.currentNode = node;
        this.tableLoading = true;
        this.getDetailSum();
        await this.getTableColumns();
        await this.getTableData();
    }

    /**
     * 获取动态表头
     */
    async getTableColumns(): Promise<any> {
        await API2.getMonitorRuleDetail(this.currentNode.ruleId).then((res: any) => {
            this.columns = this.packageColumns(res.showJson);
            this.columns.unshift(
                { field: 'rowNumber', title: '序号', width: '60' },
                { field: 'compareDetailMsg', title: '异常结果信息', width: '130' }
            );
        });
    }

    /**
     * 表格数据
     */
    async getTableData(): Promise<any> {
        this.tableLoading = true;
        await API.getMonitorResultDetail({ ruleId: this.currentNode.ruleId, showException: this.showException, paging: this.paging })
            .then((res: any) => {
                let data = [];

                // res.list = [
                //     {
                //         compareDetail: JSON.stringify(['1 +1', '2B', '2B +2']),
                //         content: JSON.stringify({ 1: '我是1', '2B': '我是22' }),
                //         rowNumber: 1,
                //         resultType: '0',
                //     },
                // ];

                if (res.list && res.list.length) {
                    res.list.forEach(element => {
                        element.contentJ = JSON.parse(element.content);

                        if (element.compareDetail) {
                            element.compareDetail = JSON.parse(element.compareDetail);
                            // 处理 异常结果信息
                            element.compareChinese = [];
                            for (let i = 0; i < element.compareDetail.length; i++) {
                                const item = element.compareDetail[i];
                                element.compareChinese.push(this.columns.find(i => item.indexOf(i.field) > -1)?.title);
                            }
                            element.compareDetailMsg = element.compareChinese.join(',');
                        }
                        data.push({ ...element.contentJ, ...element });
                    });
                }
                this.tableData = data || [];
                this.paging.total = res?.total || 0;
            })
            .finally(() => {
                this.tableLoading = false;
            });
    }

    getDetailSum(): void {
        API.getDetailSum({ ruleId: this.currentNode.ruleId }).then((res: any) => {
            // 转百分比
            this.greenNum = Number(((res.normalCount / (res.exceptionCount + res.normalCount)) * 100).toFixed(0));
            this.redNum = Number(((res.exceptionCount / (res.exceptionCount + res.normalCount)) * 100).toFixed(0));

            this.newCalcDate = dateFormat(res.newCalcDate) + ' ' + timeFormat(res.newCalcTime);
        });
    }

    handleCheck(): void {
        this.paging.currentPage = 1;
        this.getTableData();
    }

    /**
     * 将JSON转换为Columns格式
     */
    packageColumns(json): ColumnVO[] {
        // if (json && this.isJsonString(json)) {
        //     let obj = JSON.parse(json);
        //     const list = [];
        //     for (const key in obj) {
        //         list.push({ field: key, title: obj[key] });
        //     }
        //     return list;
        // }

        if (json && this.isJsonString(json)) {
            let element = JSON.parse(json);
            const list = [];
            for (let i = 0; i < element.length; i++) {
                const obj = element[i];
                for (const key in obj) {
                    list.push({ field: key, title: obj[key] });
                }
            }
            return list;
        }

        return [];
    }

    // 判断是否为json数据
    isJsonString(str: string) {
        try {
            if (typeof JSON.parse(str) == 'object') {
                return true;
            }
        } catch (e) {
            this.yh_message_error('获取表格列失败, JSON格式有误!');
        }
        return false;
    }

    rowStyle({ row }): string {
        if (row.resultType === '0') {
            return 'background: #fadcd9';
        } else {
            return '';
        }
    }
}
</script>
<style lang="scss" scoped>
#monitor-result-detail {
    width: 100%;
    height: 100%;

    .left {
        border: 1px solid #ccc;
        border-right: none;
    }

    .right {
        border: 1px solid #ccc;

        .progress {
            display: block;
            float: left;
            margin-top: 10px;
            height: 20px;
            line-height: 20px;
            color: #fff;
            text-align: center;
            font-weight: normal;
            font-size: 12px;
            border: 1px solid #ccc;
            overflow: hidden;
        }

        .progress-green {
            background: #14c489;
            width: 84px;
            border-radius: 6px 0 0 6px;
            margin-left: 10px;
            border-right: none;
        }

        .progress-red {
            background: #e05548;
            width: 50px;
            border-radius: 0 6px 6px 0;
            margin-right: 10px;
            border-left: none;
        }
    }

    .title {
        background: #e5e8eb;
        height: 40px;
        line-height: 40px;
        font-size: 14px;
        padding: 0 0 0 5px;
        border-bottom: 1px solid #ccc;
    }

    .tree {
        // border: 1px solid #ccc;
        border-top: none;

        li {
            position: relative;
            margin: 5px;
            background: #b2ebd9;
            border-radius: 5px;
            height: 30px;
            line-height: 30px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            padding-right: 50px;
            cursor: pointer;

            .name {
            }

            .sum {
                position: absolute;
                right: 0;
                background: #e05548;
                display: inline-block;
                height: 20px;
                line-height: 20px;
                margin: 5px 5px 0 0;
                border-radius: 5px;
                color: #fff;
                padding: 0 10px;
            }
        }

        li:hover,
        .current {
            background: #eceeff;
        }
    }

    .table {
        height: calc(100% - 40px);
    }
}
</style>
